//
//  DZImageFrameController.m
//  PhotoFrame
//
//  Created by ZhangJitao on 2018/10/16.
//  Copyright © 2018年 Piter Zhang. All rights reserved.
//

#import "DZImageFrameController.h"
#import "UIView+Extension.h"
#import "UIImage+PhotoFrame.h"

@interface DZImageFrameController () <UIScrollViewDelegate>

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIImageView *imageFrameImageView;

@property (nonatomic, strong) UIButton *doneButton;

@end

@implementation DZImageFrameController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
    
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}
//注释:info.plist文件中，View controller-based status bar appearance项设为YES，
//则View controller对status bar的设置优先级高于application的设置。
//为NO则以application的设置为准，view controller的prefersStatusBarHidden方法无效，是根本不会被调用的。

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 隐藏状态栏
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
        //调用隐藏方法
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    }
    
    [self initUI];
    
}

- (void)done:(UIBarButtonItem *)sender {
    
    UIImage * frmaeImage = self.imageFrameImageView.image;
    UIImage * image = [self handleImage];
    image = [image frameAddImage:frmaeImage];
    self.imageFrameImageView.image = image;
    //self.imageView.frame = self.imageFrameImageView.frame;
    
    if(self.navigationController){
        [self.navigationController popViewControllerAnimated:NO];
        if(self.imageFrameCompleteBlock){
            self.imageFrameCompleteBlock(image);
        }
    }else{
        [self dismissViewControllerAnimated:YES completion:^{
            if(self.imageFrameCompleteBlock){
                self.imageFrameCompleteBlock(image);
            }
        }];
    }
}

- (void)initUI {
    
    [self.view addSubview:self.contentView];
    [self.contentView addSubview:self.scrollView];
    [self.scrollView addSubview:self.imageView];
    [self.contentView addSubview:self.imageFrameImageView];
    
    
    self.scrollView.minimumZoomScale = 0.5;
    self.scrollView.maximumZoomScale = 3.0;
    self.scrollView.delegate = self;
    
    self.scrollView.contentSize = CGSizeMake(self.imageView.frame.size.width*self.scrollView.maximumZoomScale, self.imageView.frame.size.height*self.scrollView.maximumZoomScale);
    self.scrollView.decelerationRate = 0.0f; //减速速率
    self.scrollView.zoomScale = 1.0;
    if (@available(iOS 11.0, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    
//    UIImage * image = [UIImage imageWithContentsOfFile:self.selectedImageModel.imageLocalPath];
    UIImage *image = [UIImage imageNamed:@"1.png"];
    [self showImage:image inImageView:self.imageFrameImageView ViewSize:self.contentView.frame.size];
    
    [self showImage:self.image inImageView:self.imageView ViewSize:self.imageFrameImageView.frame.size];
    self.scrollView.frame = self.imageFrameImageView.frame;
    self.scrollView.contentSize = CGSizeMake(self.imageView.frame.size.width*self.scrollView.maximumZoomScale, self.imageView.frame.size.height*self.scrollView.maximumZoomScale);
    
    [self.view addSubview:self.doneButton];
    [self.doneButton addTarget:self action:@selector(done:) forControlEvents:UIControlEventTouchUpInside];
}

// MARK: - 显示相框 和要编辑的照片
-(void)showImage:(UIImage*)image inImageView:(UIImageView*)imageView ViewSize:(CGSize)viewSize{
    imageView.image = image;
    if(nil == image){
        return;
    }
    CGFloat imageViewWidth = 0;
    CGFloat imageViewHeight = 0;
    CGFloat imageViewLeft = 0;
    CGFloat imageViewTop = 0;
    if(image.size.width >= image.size.height){
        imageViewWidth = viewSize.width;
        imageViewHeight = imageViewWidth/image.size.width * image.size.height;
    }else{
        imageViewHeight = viewSize.height;
        imageViewWidth = imageViewHeight/image.size.height * image.size.width;
    }
    imageViewLeft = (viewSize.width - imageViewWidth)/2.0;
    imageViewTop = (viewSize.height - imageViewHeight)/2.0;
    
    CGRect imageViewFrame = CGRectMake(imageViewLeft, imageViewTop, imageViewWidth, imageViewHeight);
    imageView.frame = imageViewFrame;
}


#pragma mark - scrollView delegate
//缩放过程中的图像
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    if(scrollView != self.scrollView){
        return nil;
    }
    return self.imageView;
}

//缩放结束
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    if(scrollView != self.scrollView){
        return;
    }
    NSLog(@"缩放的比例:%f",scale);
}


//缩放中
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(scrollView != self.scrollView){
        return;
    }
    
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    self.imageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                        scrollView.contentSize.height * 0.5 + offsetY);
    NSLog(@"缩放中");
}

- (UIImage *)handleImage{
    UIImage * originalImage = self.image;
    CGFloat width = self.imageView.width;
    CGFloat rationScale = (originalImage.size.width  / width /1.0);

    CGRect currentSquareCutRect = CGRectZero;
    currentSquareCutRect.origin = self.scrollView.contentOffset;
    currentSquareCutRect.size = self.imageFrameImageView.frame.size;

    CGFloat origX = (currentSquareCutRect.origin.x - self.imageView.origin.x) * rationScale;
    CGFloat origY = (currentSquareCutRect.origin.y - self.imageView.origin.y)  * rationScale;
    CGFloat oriWidth = currentSquareCutRect.size.width * rationScale;
    CGFloat oriHeight = currentSquareCutRect.size.height * rationScale;

    CGRect myRect = CGRectMake(origX, origY, oriWidth, oriHeight);

    UIImage * image = [originalImage frameSquareClipInRect:myRect];

    return image;
}

- (UIView *)contentView {
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 150)];
    }
    return _contentView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, UIScreen.mainScreen.bounds.size.height)];
    }
    return _scrollView;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.contentView.frame), CGRectGetHeight(self.contentView.frame))];
    }
    return _imageView;
}

- (UIImageView *)imageFrameImageView {
    if (!_imageFrameImageView) {
        _imageFrameImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.contentView.frame), CGRectGetHeight(self.contentView.frame))];
    }
    return _imageFrameImageView;
}

- (UIButton *)doneButton {
    if (!_doneButton) {
        _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneButton setTitle:@"完成" forState:UIControlStateNormal];
        _doneButton.backgroundColor = [UIColor orangeColor];
        _doneButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _doneButton.frame = CGRectMake(self.view.width - 70, self.view.height - 40, 70, 40);
    }
    return _doneButton;
}

@end
